package chagine.mdt.utils;

import chagine.core.ErrorCode;
import chagine.core.util.Assert;
import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

import java.lang.reflect.Field;

public class ChaginReflectUtil {

    /**
     * 把chagine前端传的下划线字段名转成驼峰
     * @param chagineColomnName chagine前端传的下划线字段名
     */
    public static String getColomnName(String chagineColomnName) {
        // 转成java的驼峰字段名
        return StringUtils.underlineToCamel(chagineColomnName);
    }

    public static <T> T copyOneProperty(T obj1, T obj2, String chagineColomnName, Class<T> clazz) {
        String columnName = getColomnName(chagineColomnName);
        Field field = getField(clazz, columnName);
        Object fieldValue = ReflectUtil.getFieldValue(obj1, field);
        ReflectUtil.setFieldValue(obj2, field, fieldValue);
        return obj2;
    }

    public static <T, V> ColumnField getOnePropertyField(V v, String chagineColomnName, Class<T> clazz) {
        String columnName = getColomnName(chagineColomnName);
        Field vField = getField(v.getClass(), columnName);
        Object fieldValue = ReflectUtil.getFieldValue(v, vField);
        Field tField = getField(clazz, columnName);
        TableField annotation = tField.getAnnotation(TableField.class);
        Assert.error(annotation == null, ErrorCode.ILLEGALARGUMENT_EXCEPTION, "属性注解不存在");
        String tableFieldColumn = annotation.value();
        return new ColumnField(tableFieldColumn, fieldValue);
    }

    private static <T> Field getField(Class<T> clazz, String name) {
        return ReflectUtil.getField(clazz, name);
    }


    public static void main(String[] args) {
        String begenTime = getColomnName("begen_time");
        System.out.println(begenTime);
    }

    @RequiredArgsConstructor
    @Getter
    public static class ColumnField {
        private final String colomn;

        private final Object value;
    }
}
